const express = require("express");
const mongoose = require("mongoose");
const swig = require("swig");
const url = require("url");
const {findlist} = require("./handleDB.js");


let pro = new Promise((resolve,reject)=>{
    mongoose.connect("mongodb://localhost:27019",(error)=>{
        if(!error){
            console.log("连接数据库成功")
            resolve();
        }else{
            reject(error)
        }
    })
})

pro.then(
    ()=>{
        //创建服务器
        const server = express();

        //模板引擎
        server.engine("html",swig.renderFile)
        server.set("views",__dirname)
        server.set("view engine","html")
        swig.setDefaults({cahce:false})

        //写入网页
        server.get("/",(request,response)=>{
            //获取url中的page & count
            let query = url.parse(request.url,true).query;
            let page = Number(query.page) || 1;
            let count = Number(query.count) || 5;

            findlist(page,count)
            .then(
                ({result,pages})=>{
                    //每一页的下标
                    let arr = [];
                    for(let i=1;i<=pages;i++){
                        arr.push(i);
                    }

                    response.render("index",{result,arr,count,page})
                }
            )
        })


        server.listen(8080,"localhost",(error)=>{
            if(error){
                console.log("启动失败")
                console.log(error)
            }else{
                console.log("启动成功")
            }
        })
    },
    (error)=>{
        console.log("连接数据库失败")
        console.log(error)
    }
)